<?php

namespace app\admin\model;

use think\Model;
use app\admin\validate\AuthRule as ModelValidate;
class AuthRule extends Model{

  public function children(){
    return $this->hasMany('AuthRule', 'parent_id');
  }

  public function parent(){
    return $this->belongsTo('AuthRule', 'parent_id');
  }

  /**
   * 保存方法
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    array      $data 保存数据
   * @param    array      $opts 辅助信息
   * @return   array
   */
  public function saveItem($data, $opts = []){
    $res = ['status' => false, 'msg' => '保存失败'];
    if(!is_array($data)){
      $res['msg'] = '保存数据格式不正确';
    }

    if(isset($opts['id']) && $opts['id'] > 0){
      $data['id'] = $opts['id'];
    }

    $validate = new ModelValidate();
    if(!$validate->check($data)){
      $res['msg'] = $validate->getError();
      return $res;
    }

    if(isset($data['id'])){
      $this->isUpdate(true)->save($data);
      $id = $data['id'];
      $msg = '更新成功';
    }else{
      $this->isUpdate(false)->save($data);
      $id = $this->id;
      $msg = '添加成功';
    }
    $res = ['status' => true, 'msg' => $msg];
    if(isset($opts['is_return']) && $opts['is_return']){
      $res['data'] = $this->where('id', $id)->find();
    }
    return $res;
  }

  /**
   * 删除记录
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    integer    $id 删除元素主键
   * @return   array
   */
  public function deleteItem($id){
    $res = ['status' => false, 'msg' => '删除失败'];
    if(!is_numeric($id)){
      $res['msg'] = '删除参数错误';
      return $res;
    }

    $item = $this->where('id', $id)->find();
    if(empty($item)){
      $res['msg'] = '删除记录不存在';
      return $res;
    }

    $child_count = $item->children()->count();
    if($child_count){
      $res['msg'] = '该记录有子菜单，不能删除';
      return $res;
    }

    $item->delete();

    $res = ['status' => true, 'msg' => '删除成功'];
    return $res;
  }

  /**
   * 树状结构菜单
   * @Author zhanghong
   * @Date   2017-01-01
   * @param  string     $rule_type 菜单类型
   * @param  integer    $parent_id 根结点ID
   * @param  boolean    $skip_hide 是否忽略隐藏结点
   * @param  integer    $level     结点深度
   * @return array                 Tree
   */
  public function findWithDescendants($rule_type, $parent_id = 0, $skip_hide = true, $level = 0){
    $map = [];
    $map['rule_type'] = ['rule_type', '=', $rule_type];
    $map['parent_id'] = ['parent_id', '=', $parent_id];
    if($skip_hide){
      $map['status'] = ['status', '=', 1];
    }
    $order_str = $this->orderStr('default');
    $children = $this->where($map)->order($order_str)->select();
    if(!empty($children)){
      //如果有子类
      foreach ($children as $key => &$child) {
        $child['deep_level'] = $level;
        $child['children'] = $this->findWithDescendants($rule_type, $child['id'], $skip_hide, $level+1);
      }
    }
    return $children;
  }

  /**
   * 一维数组结构菜单
   * @Author zhanghong
   * @Date   2017-01-01
   * @param  string     $rule_type 菜单类型
   * @param  array      $list      保存菜单的数组
   * @param  integer    $parent_id 根结点ID
   * @param  array      $ancestor_ids 所有祖先结点ID
   * @param  string     $prefix       显示名前辍
   * @return array                    Rule集合
   */
  public function explandWithDescendants($rule_type, $list, $parent_id = 0, $ancestor_ids = [], $prefix=''){
    $order_str = $this->orderStr('default');
    $children = $this->where('rule_type', $rule_type)->where('parent_id', $parent_id)->order($order_str)->select();
    if(!empty($children)){
      //如果有子类
      $level = count($ancestor_ids);
      foreach ($children as $key => $child) {

        $child['deep_level'] = $level;
        $child['shown_title'] = $prefix.$child['title'];
        $list[] = $child;

        $sub_ancestor_ids = $ancestor_ids;
        array_push($sub_ancestor_ids, $child['id']);
        //所有祖先结点和自己的ID列表
        $child['with_ancestor_ids'] = $sub_ancestor_ids;
        if($level == 0){
          //第二级菜单
          $sub_prefix = '┗━';
        }else if($level > 0){
          //第二级以后的菜单
          $sub_prefix = '&nbsp;&nbsp;&nbsp;&nbsp;'.$prefix;
        }
        $list = $this->explandWithDescendants($rule_type, $list, $child['id'], $sub_ancestor_ids, $sub_prefix);
      }
    }
    return $list;
  }

  /**
   * 排序方式
   * @Author   zhanghong
   * @DateTime 2018-03-04
   * @param    string     $order_type 排序类型
   * @return   string
   */
  protected function orderStr($order_type = 'default'){
    switch ($order_type) {
    default:
      $order_str = 'sort ASC, id DESC';
      break;
    }

    return $order_str;
  }
}
